#include "strstr.h"

char * strrep(register char * string, register char * target, register char * value)
{
	while (strstr(string, target) != NULL)
	{
		register int start = strstr(string, target) - string;
		register char * front = strmid(string, 0, start);
		register char * tail = strmid(string, start + strlen(target), strlen(string));
		front = (char*)realloc(front, sizeof(char) * (strlen(front) + strlen(value) + strlen(tail)));
		strcat(front, value);
		strcat(front, tail);
		string = front;
	}
	return string;
}
char * strsep(register char **string, register const char *delim, register char * delimReturn)
{
	register char *s;
	register const char *spanp;
	register int c, sc;
	char *tok;

	if ((s = *string) == NULL)
		return (NULL);

	for (tok = s;;)
	{
		c = *s++;
		spanp = delim;
		do {
			if ((sc = *spanp++) == c)
			{
				if (!c) s = NULL;
				else s[-1] = 0;
				*string = s;
				if (delimReturn != NULL)
					*delimReturn = c;
				return (tok);
			}
		} while (sc);
	}
}
char * chrstr(register char ch)
{
	register char * string = (char*)malloc(sizeof(char) * 2);
	string[0] = ch;
	string[1] = 0;
	return string;
}
char * strmid(register char * string, register int start, register int len)
{
	register char * str = (char *)malloc(sizeof(char) * strlen(string));
	if (start > (int)strlen(string)) return "";
	for (register int i = start; (i < len + start) && strlen(string); i++)
		str[i - start] = string[i];
	if (len < 0) return "";
	else str[len] = 0;
	return str;
}
char * trim(register char * string)
{
	if (!(strlen(string) - 1))
		if (string[0] != ' ')
			return chrstr(string[0]);
		else
			return "";
	else
		if (string[0] != ' ')
			return strcat(chrstr(string[0]), trim(strmid(string, 1, strlen(string) - 1)));
		else
			return trim(strmid(string, 1, strlen(string) - 1));
}
char * trimLR(register char * string, register int type)
{
	for (int i = 0; i < (int)strlen(string); i++)
	{
		if (string[i] != ' ' && !type)
			return strmid(string, i, strlen(string) - i - 1);
		if (string[strlen(string) - i - 1] != ' ' && type)
			return strmid(string, 0, strlen(string) - i);
	}
	return string;
}